package org.whuims.web.util;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author Angela
 */
@Component
public class DocumentExtractor {

    @Autowired
    private HttpServletRequest request;

    public static void main(String[] args) throws IOException, TikaException {
        System.out.println(new Tika().parseToString(new File("/Users/zhaozhongwei/Desktop/阿里巴巴Java开发手册.pdf")));
    }

    public String extract(String filename) {
        String content = "";
        Tika tika = new Tika();
        try {
            filename = request.getServletContext().getRealPath("/") + "resource/docs/" + filename;
            if (filename.contains(".docx")) {
                XWPFDocument doc = new XWPFDocument(new FileInputStream(new File(filename)));
                XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
                content = extractor.getText();
            } else content = tika.parseToString(new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TikaException e) {
            e.printStackTrace();
        }
        return content;
    }

    public String extract(File file) {
        String content = "";
        Tika tika = new Tika();
        try {
            String fileName = file.getName();
            if (fileName.contains(".docx")) {
                XWPFDocument doc = new XWPFDocument(new FileInputStream(file));
                XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
                content = extractor.getText();
            } else content = tika.parseToString(file);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TikaException e) {
            e.printStackTrace();
        }
        return content;
    }

}